package logs

import (
	"errors"
	"fmt"
	"gitee.com/freedom_feel/gui-bos-api/global"
	"os"
	"path/filepath"
	"time"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var log *zap.Logger
var Logerr *zap.Logger

func Info(msg any, fields ...zap.Field) {
	log.Info(msg.(string), fields...)
}

func Error(msg any, fields ...zap.Field) {
	log.Error(msg.(string), fields...)
}

func LogInit() {
	// 确保日志目录存在
	if err := os.MkdirAll(global.DefaultLogPath, os.ModePerm); err != nil {
		panic(err)
	}
	// 获取当前日志录下的文件信息 检查文件大小是否超过阈值
	file, err := getCurrentLogFile(global.DefaultLogPath)
	if err != nil {
		panic(err)
	}
	//上面没有遍历到 创建
	if file == nil {
		// 创建一个新的日志文件
		file, err = CreatOpenFile(createNewLogFile(global.DefaultLogPath))
		if err != nil {
			panic(err)
		}
	}

	// 配置 Zap 的 EncoderConfig 和核心
	encoderConfig := zapcore.EncoderConfig{
		MessageKey:     "msg",
		LevelKey:       "level",
		TimeKey:        "ts",
		NameKey:        "logger",
		CallerKey:      "caller",
		FunctionKey:    "function",
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeTime:     zapcore.ISO8601TimeEncoder,
		EncodeDuration: zapcore.StringDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}

	core := zapcore.NewCore(
		zapcore.NewConsoleEncoder(encoderConfig),
		zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(file)),
		zap.NewAtomicLevelAt(zap.InfoLevel),
	)

	log = zap.New(core, zap.AddCaller(), zap.AddCallerSkip(2))
	Logerr = zap.New(core, zap.AddCaller(), zap.AddCallerSkip(2))
	log.Info("log init success")
}

func getCurrentLogFile(logDir string) (*os.File, error) {
	var logFile *os.File
	logFiles, err := os.ReadDir(logDir)
	if err != nil {
		return nil, err
	}
	for _, lf := range logFiles {
		if !lf.IsDir() {
			fileName := lf.Name()
			fileInfo, ifErr := lf.Info()
			if ifErr != nil {
				continue
			}
			//fmt.Println(strconv.FormatInt(fileInfo.Size(), 10))
			if fileInfo.Size() > global.MaxFileSize && len(fileName) == 15 {
				newName := filepath.Join(logDir, UpFileName(fileInfo.ModTime()))
				oldName := filepath.Join(logDir, fileName)
				os.Rename(oldName, newName)
				return nil, nil
			}
		}
	}
	// 如果没有日志文件，创建一个新的日志文件
	logFile, err = CreatOpenFile(createNewLogFile(global.DefaultLogPath))
	if err != nil {
		return nil, err
	}
	return logFile, nil
}

func createNewLogFile(logDir string) (logFileName string) {
	return filepath.Join(logDir, "gui-bos-api.log")
}

func UpFileName(timestamp time.Time) (logFileName string) {
	timestampStr := timestamp.Format("2006-01-02-15-04-05")
	logFileName = fmt.Sprintf("gui-bos-api-%s.log", timestampStr)
	return logFileName
}

func CreatOpenFile(fileName string) (*os.File, error) {
	stdoutFile, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		fmt.Printf("创建标准输出文件时出错: %v\n", err)
		return nil, errors.New("创建标准输出文件时出错")
	}
	return stdoutFile, nil
}
